package com.zmn.mcc.dubbo.impl.role;

import com.alibaba.fastjson.JSON;
import com.zmn.base.plat.engine.common.constant.PlatEngineConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.mcc.business.interfaces.role.RoleBService;
import com.zmn.mcc.business.interfaces.role.RoleChangeLogBService;
import com.zmn.mcc.common.dto.cc.CCRoleDRO;
import com.zmn.mcc.common.dto.cc.CCRolePermitDRO;
import com.zmn.mcc.common.dto.cc.CCRoleStaffDRO;
import com.zmn.mcc.common.dto.cc.UpdateQuery;
import com.zmn.mcc.common.dto.role.*;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.mcc.dubbo.interfaces.role.RoleListRemoteService;
import com.zmn.mcc.model.entity.role.*;
import com.zmn.mcc.permit.client.aop.BasePermitProcess;
import com.zmn.mcc.services.interfaces.role.RolePermitService;
import com.zmn.mcc.services.interfaces.role.RoleService;
import com.zmn.mcc.services.interfaces.role.RoleStaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author tanbiao
 * @description
 * @modifier
 * @since 2020/7/3 16:18
 **/
@Service(version = DubboConsts.INTERFACE_VERSION, validation = "true")
@Slf4j
public class RoleListRemoteServiceImpl implements RoleListRemoteService {
    private final Logger logger = LoggerFactory.getLogger(RoleListRemoteServiceImpl.class);

    private static final String TAG = "角色dubbo接口";

    @Resource
    private RoleBService roleBService;
    @Resource
    private RoleService roleService;

    @Resource
    private RolePermitService rolePermitService;

    @Resource
    private RoleStaffService roleStaffService;
    @Resource
    private RoleChangeLogBService roleChangeLogBService;


    @Override
    @ReadOnlyConnection
    public ResponseDTO<List<RoleDRO>> listByDIO(RoleDIO roleDIO) {
        logger.debug("listByDIO 输入参数为：{}", JSON.toJSONString(roleDIO));

        if (NumberUtil.isNullOrZero(roleDIO.getStatus())) {
            return ResponseDTO.fail("没有指定角色状态");
        }

        try {
            List<RoleDRO> retList = roleBService.listByDIO(roleDIO);
            return ResponseDTO.success(retList, "OK");
        } catch (Exception e) {
            logger.error(TAG, e);
            return ResponseDTO.fail("角色dubbo接口失败");
        }

    }

    @Override
    public ResponseDTO<List<RoleDRO>> listByIds(List<Integer> ids) {
        logger.debug("listByDIO 输入参数为：{}", ids);

        try {
            List<RoleDRO> roles = roleBService.listByIds(ids);

            return ResponseDTO.success(roles, "OK");
        } catch (Exception e) {
            logger.error(TAG, e);
            return ResponseDTO.fail("角色dubbo接口失败");
        }
    }

    @Override
    public ResponseDTO<List<RoleBaseDRO>> listByDeptIds(List<Integer> deptIds) {

        if (deptIds == null || deptIds.size() == 0) {
            return ResponseDTO.fail("必要参数为空");
        }
        if (deptIds.size() > BasePermitProcess.MAX_PERMIT_COUNT) {
            return ResponseDTO.fail("每页最大500条数据");
        }
        List<McRole> roleList = roleService.listByDeptIds(deptIds, GlobalConsts.YES);
        List<RoleBaseDRO> roleBaseList = new ArrayList<>(roleList.size());
        roleList.forEach(r -> {
            RoleBaseDRO roleBase = RoleBaseDRO.builder()
                    .roleId(r.getRoleId())
                    .roleName(r.getRoleName())
                    .deptId(r.getDeptId())
                    .build();
            roleBaseList.add(roleBase);
        });
        return ResponseDTO.success(roleBaseList, "OK");
    }

    @Override
    public ResponseDTO<LayuiTableDO<RoleBaseDRO>> listByPageSearch(RoleSearchDIO dio) {

        McRoleQuery query = new McRoleQuery();
        query.setRoleName(dio.getSearchVal());
        query.setPageIndex(dio.getPageIndex());
        query.setPageSize(dio.getPageSize());
        query.setStatus(GlobalConsts.YES);
        List<McRole> roleList = roleService.listPageByQuery(query);
        List<RoleBaseDRO> roleBaseList = new ArrayList<>(roleList.size());
        roleList.forEach(r -> {
            RoleBaseDRO roleBase = RoleBaseDRO.builder()
                    .roleId(r.getRoleId())
                    .roleName(r.getRoleName())
                    .deptId(r.getDeptId())
                    .build();
            roleBaseList.add(roleBase);
        });
        LayuiTableDO<RoleBaseDRO> table = new LayuiTableDO<>();
        table.setCount(query.getTotalCount());
        table.setData(roleBaseList);
        return ResponseDTO.success(table, "OK");
    }

    @Override
    public ResponseDTO<List<CCRoleDRO>> listRoleByUpdateTime(UpdateQuery query) {

        if (Objects.isNull(query.getFrom()) || Objects.isNull(query.getTo())) {
            return ResponseDTO.fail("更新起止时间不能为空");
        }
        try {
            McRoleQuery query2 = new McRoleQuery();
            BeanUtils.copyProperties(query, query2);
            List<McRole> result = Optional.ofNullable(roleService.listPageByQuery(query2)).orElse(Collections.emptyList());
            List<CCRoleDRO> result2 = BeanMapper.mapList(result, CCRoleDRO.class);
            return ResponseDTO.success(result2);
        } catch (BeansException e) {
            log.error("listRoleByUpdateTime查询失败,原因:{}", e.getMessage(), e);
            return ResponseDTO.fail("查询失败，程序异常");
        }
    }

    @Override
    public ResponseDTO<List<CCRolePermitDRO>> listRolePermitByUpdateTime(Integer pageSize, Integer pageIndex) {

        if (NumberUtil.isNullOrZero(pageSize)) {
            pageSize = 100;
        }
        if (NumberUtil.isNullOrZero(pageIndex)) {
            pageIndex = 1;
        }
        try {
            int startIndex = (pageIndex > 0 ? pageIndex - 1 : 0) * pageSize;
            List<McRolePermit> result = Optional.ofNullable(rolePermitService.listPage(startIndex, pageSize)).orElse(Collections.emptyList());
            List<CCRolePermitDRO> result2 = BeanMapper.mapList(result, CCRolePermitDRO.class);
            return ResponseDTO.success(result2);
        } catch (BeansException e) {
            log.error("listRolePermitByUpdateTime查询失败,原因:{}", e.getMessage(), e);
            return ResponseDTO.fail("查询失败，程序异常");
        }
    }

    @Override
    public ResponseDTO<List<CCRoleStaffDRO>> listRoleStaffByUpdateTime(Integer pageSize, Integer pageIndex) {

        if (NumberUtil.isNullOrZero(pageSize)) {
            pageSize = 100;
        }
        if (NumberUtil.isNullOrZero(pageIndex)) {
            pageIndex = 1;
        }
        try {
            int startIndex = (pageIndex > 0 ? pageIndex - 1 : 0) * pageSize;
            List<McRoleStaff> result = Optional.ofNullable(roleStaffService.listPage(startIndex, pageSize)).orElse(Collections.emptyList());
            List<CCRoleStaffDRO> result2 = BeanMapper.mapList(result, CCRoleStaffDRO.class);
            return ResponseDTO.success(result2);
        } catch (BeansException e) {
            log.error("listRoleStaffByUpdateTime查询失败,原因:{}", e.getMessage(), e);
            return ResponseDTO.fail("查询失败，程序异常");
        }
    }

    @Override
    public ResponseDTO<List<RoleBaseDRO>> listRoleByStaffId(Integer staffId) {

        McRoleQuery query = new McRoleQuery();
        query.setStaffId(staffId);
        query.setStatus(PlatEngineConsts.STATUS_VALID);
        query.setNumber(DubboConsts.DUBBO_RESULT_MAX_NUMBER);
        List<McRole> mcRoles = roleService.listByQuery(query);
        if (CollectionUtil.isNullOrEmpty(mcRoles)) {
            return ResponseDTO.success(Collections.emptyList());
        }
        return ResponseDTO.success(BeanMapper.mapList(mcRoles, RoleBaseDRO.class));
    }

    @Override
    public ResponseDTO<List<McRoleChangeLogDRO>> listRoleChangeLog(McRoleChangeLogDIO dio) {
        List<McRoleChangeLog> mcRoleChangeLogs = roleChangeLogBService.listRoleChangeLog(dio);
        if (CollectionUtil.isNullOrEmpty(mcRoleChangeLogs)) {
            return ResponseDTO.success(Collections.emptyList());
        }
        return ResponseDTO.success(BeanMapper.mapList(mcRoleChangeLogs, McRoleChangeLogDRO.class));
    }
}
